package com.jason.exp.filter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;

public class LogFilter implements Filter {
	
	static final String REFERER = "Referer";
	static final String USER_AGENT = "User-Agent";
	
	final Logger logger = LoggerFactory.getLogger(LogFilter.class);

	public void init(FilterConfig filterConfig) throws ServletException {

	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		
		String remoteAddr = httpServletRequest.getRemoteAddr();
		String serverName = httpServletRequest.getServerName();
		String localAddr = httpServletRequest.getLocalAddr();
		String localName = httpServletRequest.getLocalName();
		StringBuffer url = httpServletRequest.getRequestURL();
		
		Enumeration<String> headerKeys = httpServletRequest.getHeaderNames();
		Map<String, String> header = Maps.newHashMap();
		while (headerKeys.hasMoreElements()) {
			String key = headerKeys.nextElement();
			header.put(key, httpServletRequest.getHeader(key));
			logger.debug("{} : {}", key, httpServletRequest.getHeader(key));
		}
		
		Enumeration<String> parameterNames = httpServletRequest.getParameterNames();
		Map<String, String> param = Maps.newHashMap();
		while (parameterNames.hasMoreElements()) {
			String parameterName = parameterNames.nextElement();
			param.put(parameterName, httpServletRequest.getParameter(parameterName));
			logger.debug("{} : {}", parameterName, httpServletRequest.getParameter(parameterName));
		}
		
		AccessInfo accessInfo = new AccessInfo();
		accessInfo.setHeader(header);
		accessInfo.setParam(param);
		accessInfo.setLocalAddr(localAddr);
		accessInfo.setLocalName(localName);
		accessInfo.setServerName(serverName);
		accessInfo.setRemoteAddr(remoteAddr);
		accessInfo.setUrl(url.toString());
		accessInfo.setReferer(header.get(REFERER));
		accessInfo.setUserAgent(header.get(USER_AGENT));
		logger.info("access info : {}", accessInfo);
		
		chain.doFilter(request, response);
	}

	public void destroy() {

	}

}
